package com.doghome.testsecurity.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

@Component
public class MyTokenFilter extends GenericFilterBean {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Cookie[] cookies = req.getCookies();
        String token = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase("token")) {
                    token = cookie.getValue();
                    break;
                }
            }
        }

        if (token != null && redisTemplate.hasKey(token)) {
            Map<String, Object> map = (Map<String, Object>) redisTemplate.opsForValue().get(token);
            //放回到security的上下文中
            SecurityContextHolder.getContext().setAuthentication((Authentication) map.get("AuthToken"));
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
